from aiogram import types
from aiogram_dialog import DialogManager, StartMode

from poker_bot.core.exceptions.user import UserTgIdAlreadyExist
from poker_bot.core.models.enums.account import AccountStatus
from poker_bot.database.services import AccountService, UserService
from poker_bot.tg_bot.states import ClientSG


async def user_start(
    message: types.Message | types.CallbackQuery,
    dialog_manager: DialogManager,
    user_service: UserService,
    account_service: AccountService,
):
    user_id = message.from_user.id
    username = message.from_user.username
    if not username:
        username = message.from_user.first_name
    try:
        await user_service.create_user(
            telegram_id=user_id,
            username=username,
        )
    except UserTgIdAlreadyExist:
        pass

    user = await user_service.get_user_by_telegram_id(user_id)
    user_accounts = await account_service.get_user_accounts(user_id)

    if isinstance(message, types.CallbackQuery):
        await message.message.delete()
    if not user.selected_account_id:
        await dialog_manager.start(ClientSG.start_question, mode=StartMode.RESET_STACK)
    elif not any(
        [account.status == AccountStatus.approved for account in user_accounts]
    ):
        await message.answer("Ожидайте модерации аккаунта")  # TODO Заменить сообщение
        return
    else:
        await dialog_manager.start(ClientSG.start, mode=StartMode.RESET_STACK)
